package ui;

import burp.api.montoya.MontoyaApi;
import burp.api.montoya.http.message.HttpHeader;
import burp.api.montoya.http.message.HttpRequestResponse;
import burp.api.montoya.http.message.requests.HttpRequest;
import burp.api.montoya.http.message.responses.HttpResponse;
import utils.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class PermissionTestPanel extends JPanel {

    private final MontoyaApi montoyaApi;
    private JTable requestTable;
    private JPanel rightPanel;
    private DefaultTableModel tableModel;
    private final List<HttpRequestResponse> requestResponseList = new ArrayList<>();
    private final List<HttpRequestResponse> modifiedRequestResponseList = new ArrayList<>();
    private final List<HttpRequestResponse> unauthorizedRequestResponseList = new ArrayList<>();

    // 文本区域引用，用于显示请求和响应
    private JTextArea originalRequestTextArea;
    private JTextArea originalResponseTextArea;
    private JTextArea modifiedRequestTextArea;
    private JTextArea modifiedResponseTextArea;
    private JTextArea unauthorizedRequestTextArea;
    private JTextArea unauthorizedResponseTextArea;

    // 为结果列创建专门的渲染器实例
    private final List<ColorTableCellRenderer> lowPrivilegeRenderers = new ArrayList<>();
    private final List<ColorTableCellRenderer> unauthorizedRenderers = new ArrayList<>();

    // 添加对规则面板的引用
    private ConfigPanel configPanel;

    // 创建If-Modified-Since和If-None-Match请求头
    HttpHeader modifiedSinceHeader = HttpHeader.httpHeader("If-Modified-Since", "");
    HttpHeader ifNoneMatchHeader = HttpHeader.httpHeader("If-None-Match", "");

    // 在类中添加线程池
    private ExecutorService testExecutor;

    public PermissionTestPanel(MontoyaApi montoyaApi) {
        this.montoyaApi = montoyaApi;

        // 设置布局
        setLayout(new BorderLayout());

        // 初始化组件
        initializeComponents();
    }

    // 添加获取表格模型的方法
    public DefaultTableModel getTableModel() {
        return tableModel;
    }

    // 添加获取指定列渲染器的方法
    public List<ColorTableCellRenderer> getRenderersForColumn(int columnIndex) {
        return switch (columnIndex) {
            case 6 -> // 低权限结果列
                    lowPrivilegeRenderers;
            case 7 -> // 未授权结果列
                    unauthorizedRenderers;
            default -> null;
        };
    }

    private void initializeComponents() {
        // 初始化请求列表
        initializeRequestTable();

        // 创建主分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(0.5);
        splitPane.setResizeWeight(0.6);
        splitPane.setBorder(BorderFactory.createEmptyBorder());

        // 左侧是请求列表
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.add(new JScrollPane(requestTable), BorderLayout.CENTER);
        splitPane.setLeftComponent(leftPanel);

        // 右侧是带标签的面板
        initializeRightPanel();
        splitPane.setRightComponent(rightPanel);

        add(splitPane, BorderLayout.CENTER);
    }

    private void initializeRequestTable() {
        // 定义表格列
        String[] columnNames = {
                "序号", "方法", "URL",
                "原始响应长度", "低权限响应长度", "未授权响应长度",
                "低权限结果", "未授权结果"};

        // 创建表格模型
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 表格不可编辑
                return false;
            }
        };

        // 创建表格
        requestTable = new JTable(tableModel);
        // 所有列平均分配剩余宽度
        requestTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

        // 设置列宽
        setColumnWidths();

        // 添加选择监听器
        requestTable.getSelectionModel().addListSelectionListener(event -> {
            // 确保只处理一次事件，避免重复处理
            if (!event.getValueIsAdjusting()) {
                int selectedRow = requestTable.getSelectedRow();
                if (selectedRow >= 0 && selectedRow < requestResponseList.size()) {
                    LoggerUtil.logOutput("PermissionTestPanel: table clicked");
                    displayRequestResponse(selectedRow);
                }
            }
        });

        // 添加滚动面板
        JScrollPane scrollPane = new JScrollPane(requestTable);
        add(scrollPane, BorderLayout.CENTER);
    }

    private void setColumnWidths() {
        // 设置各列宽度
        requestTable.getColumnModel().getColumn(0).setPreferredWidth(50);
        requestTable.getColumnModel().getColumn(1).setPreferredWidth(50);
        requestTable.getColumnModel().getColumn(2).setPreferredWidth(500);
        requestTable.getColumnModel().getColumn(3).setPreferredWidth(100);
        requestTable.getColumnModel().getColumn(4).setPreferredWidth(110);
        requestTable.getColumnModel().getColumn(5).setPreferredWidth(110);
        requestTable.getColumnModel().getColumn(6).setPreferredWidth(100);
        requestTable.getColumnModel().getColumn(7).setPreferredWidth(100);
    }

    private void initializeRightPanel() {
        rightPanel = new JPanel(new BorderLayout());

        // 创建标签面板
        JTabbedPane tabbedPane = new JTabbedPane();

        // 创建请求/响应插件面板
        JPanel requestResponsePanel = createRequestResponsePanel();
        tabbedPane.addTab("请求/响应内容", requestResponsePanel);

        // 创建配置中心面板
        JPanel configPanel = createConfigPanel();
        tabbedPane.addTab("配置中心", configPanel);

        // 添加保存/恢复标签页
        SaveRestorePanel saveRestorePanel = new SaveRestorePanel();
        saveRestorePanel.setPermissionTestPanel(this); // 设置引用关系
        tabbedPane.addTab("保存/恢复", saveRestorePanel);

        rightPanel.add(tabbedPane, BorderLayout.CENTER);
    }

    private JPanel createRequestResponsePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建子标签页面板
        JTabbedPane subTabbedPane = new JTabbedPane();

        // 创建"原始请求"标签页
        JPanel originalRequestPanel = createOriginalRequestResponsePanel();
        subTabbedPane.addTab("原始请求", originalRequestPanel);

        // 创建"低权限请求"标签页
        JPanel modifiedRequestPanel = createModifiedRequestResponsePanel();
        subTabbedPane.addTab("低权限请求", modifiedRequestPanel);

        // 创建"未授权请求"标签页
        JPanel unauthorizedRequestPanel = createUnauthorizedRequestResponsePanel();
        subTabbedPane.addTab("未授权请求", unauthorizedRequestPanel);

        panel.add(subTabbedPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createOriginalRequestResponsePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建上下分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setDividerLocation(0.5);
        splitPane.setResizeWeight(0.5);

        // 上部分：请求信息
        JPanel requestPanel = new JPanel(new BorderLayout());
        requestPanel.setBorder(BorderFactory.createTitledBorder("请求信息"));
        originalRequestTextArea = new JTextArea();
        originalRequestTextArea.setEditable(false);
        requestPanel.add(new JScrollPane(originalRequestTextArea), BorderLayout.CENTER);

        // 下部分：响应信息
        JPanel responsePanel = new JPanel(new BorderLayout());
        responsePanel.setBorder(BorderFactory.createTitledBorder("响应信息"));
        originalResponseTextArea = new JTextArea();
        originalResponseTextArea.setEditable(false);
        responsePanel.add(new JScrollPane(originalResponseTextArea), BorderLayout.CENTER);

        splitPane.setTopComponent(requestPanel);
        splitPane.setBottomComponent(responsePanel);

        panel.add(splitPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createModifiedRequestResponsePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建上下分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setDividerLocation(0.5);
        splitPane.setResizeWeight(0.5);

        // 上部分：请求信息
        JPanel requestPanel = new JPanel(new BorderLayout());
        requestPanel.setBorder(BorderFactory.createTitledBorder("请求信息"));
        modifiedRequestTextArea = new JTextArea();
        modifiedRequestTextArea.setEditable(false);
        requestPanel.add(new JScrollPane(modifiedRequestTextArea), BorderLayout.CENTER);

        // 下部分：响应信息
        JPanel responsePanel = new JPanel(new BorderLayout());
        responsePanel.setBorder(BorderFactory.createTitledBorder("响应信息"));
        modifiedResponseTextArea = new JTextArea();
        modifiedResponseTextArea.setEditable(false);
        responsePanel.add(new JScrollPane(modifiedResponseTextArea), BorderLayout.CENTER);

        splitPane.setTopComponent(requestPanel);
        splitPane.setBottomComponent(responsePanel);

        panel.add(splitPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createUnauthorizedRequestResponsePanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 创建上下分割面板
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setDividerLocation(0.5);
        splitPane.setResizeWeight(0.5);

        // 上部分：请求信息
        JPanel requestPanel = new JPanel(new BorderLayout());
        requestPanel.setBorder(BorderFactory.createTitledBorder("请求信息"));
        unauthorizedRequestTextArea = new JTextArea();
        unauthorizedRequestTextArea.setEditable(false);
        requestPanel.add(new JScrollPane(unauthorizedRequestTextArea), BorderLayout.CENTER);

        // 下部分：响应信息
        JPanel responsePanel = new JPanel(new BorderLayout());
        responsePanel.setBorder(BorderFactory.createTitledBorder("响应信息"));
        unauthorizedResponseTextArea = new JTextArea();
        unauthorizedResponseTextArea.setEditable(false);
        responsePanel.add(new JScrollPane(unauthorizedResponseTextArea), BorderLayout.CENTER);

        splitPane.setTopComponent(requestPanel);
        splitPane.setBottomComponent(responsePanel);

        panel.add(splitPane, BorderLayout.CENTER);
        return panel;
    }

    // 创建配置中心面板
    private JPanel createConfigPanel() {
        configPanel = new ConfigPanel();
        // 设置事件监听器
        configPanel.setStartTestActionListener(e -> performTest());
        configPanel.setClearListActionListener(e -> {
            // 清空表格数据
            tableModel.setRowCount(0);
            // 清空请求响应列表
            requestResponseList.clear();
            modifiedRequestResponseList.clear();
            unauthorizedRequestResponseList.clear();
            // 清空文本显示区域
            clearTextAreas();
            // 清空渲染器列表
            lowPrivilegeRenderers.clear();
            unauthorizedRenderers.clear();
        });
        return configPanel;
    }

    // 清空所有文本显示区域的方法
    private void clearTextAreas() {
        if (originalRequestTextArea != null) originalRequestTextArea.setText("");
        if (originalResponseTextArea != null) originalResponseTextArea.setText("");
        if (modifiedRequestTextArea != null) modifiedRequestTextArea.setText("");
        if (modifiedResponseTextArea != null) modifiedResponseTextArea.setText("");
        if (unauthorizedRequestTextArea != null) unauthorizedRequestTextArea.setText("");
        if (unauthorizedResponseTextArea != null) unauthorizedResponseTextArea.setText("");
    }

    // 将请求信息添加到表格中
    public void addRequestsToTable(List<HttpRequestResponse> requests) {
        for (HttpRequestResponse requestResponse : requests) {
            requestResponseList.add(requestResponse);
            HttpRequest request = requestResponse.request();
            HttpResponse response = requestResponse.response();

            // 获取响应长度
            String responseLength = "";
            if (response != null) {
                responseLength = RequestUtil.getResponseLength(response);
            }

            Object[] rowData = new Object[]{
                    tableModel.getRowCount() + 1,
                    request.method(),
                    request.url(),
                    responseLength,
                    "",
                    "",
                    "",
                    ""
            };
            tableModel.addRow(rowData);
        }

        // 更新渲染器列表大小以匹配行数
        updateRenderers();
    }

    // 更新渲染器列表大小
    private void updateRenderers() {
        // 确保渲染器列表大小与行数一致
        while (lowPrivilegeRenderers.size() < tableModel.getRowCount()) {
            lowPrivilegeRenderers.add(new ColorTableCellRenderer());
        }
        while (unauthorizedRenderers.size() < tableModel.getRowCount()) {
            unauthorizedRenderers.add(new ColorTableCellRenderer());
        }

        // 为结果列设置渲染器
        ColorTableCellRenderer.setColumnRenderer(requestTable, 6, lowPrivilegeRenderers);
        ColorTableCellRenderer.setColumnRenderer(requestTable, 7, unauthorizedRenderers);
    }

    // 开始测试
    private void performTest() {
        LoggerUtil.logOutput("开始执行测试...");

        // 获取临时请求头内容
        String tempHeaders = configPanel.getTempHeaders();
        if (tempHeaders == null || tempHeaders.trim().isEmpty()) {
            LoggerUtil.logOutput("未设置临时请求头");
            return;
        }

        // 解析临时请求头
        List<String> headerLines = tempHeaders.lines()
                .map(String::trim)
                .filter(line -> !line.isEmpty())
                .collect(Collectors.toList());

        // 获取"检查未授权"复选框的状态
        boolean isUnauthorizedCheckSelected = configPanel.isUnauthorizedCheckSelected();
        
        // 获取"忽略请求响应码204|304"复选框的状态
        boolean isIgnore204304Checked = configPanel.isIgnore204304Checked();

        // 保存对外部类方法的引用
        Runnable updateRenderersRef = this::updateRenderers;

        // 初始化线程池，控制并发数为10
        testExecutor = Executors.newFixedThreadPool(10);

        // 使用SwingWorker执行测试，避免阻塞UI线程
        SwingWorker<Void, Void> worker = new SwingWorker<>() {
            @Override
            protected Void doInBackground() {
                // 创建CompletableFuture列表来管理并发任务
                List<CompletableFuture<Void>> futures = new ArrayList<>();

                // 对每个原始请求创建并发任务
                for (int i = 0; i < requestResponseList.size(); i++) {
                    final int index = i;
                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> processRequest(
                        index,
                        headerLines,
                        isUnauthorizedCheckSelected,
                        isIgnore204304Checked,
                        updateRenderersRef
                    ), testExecutor);
                    futures.add(future);
                }

                // 等待所有任务完成
                CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
                
                return null;
            }

            @Override
            protected void done() {
                // 关闭线程池
                if (testExecutor != null && !testExecutor.isShutdown()) {
                    testExecutor.shutdown();
                    try {
                        if (!testExecutor.awaitTermination(5, TimeUnit.SECONDS)) {
                            testExecutor.shutdownNow();
                        }
                    } catch (InterruptedException e) {
                        testExecutor.shutdownNow();
                        Thread.currentThread().interrupt();
                    }
                }
                
                try {
                    // 检查是否有异常
                    get();
                    LoggerUtil.logOutput("测试执行完成");
                } catch (Exception e) {
                    LoggerUtil.logError("测试执行出错: " + e.getMessage());
                }

                // 如果当前选中了某行，则更新显示
                int selectedRow = requestTable.getSelectedRow();
                displayRequestResponse(selectedRow);

                // 如果没有选中行但有请求，则默认显示第一行
                if (selectedRow < 0 && !requestResponseList.isEmpty()) {
                    displayRequestResponse(0);
                }
            }
        };

        // 启动后台任务
        worker.execute();
    }


    // 修改请求头
    private HttpRequest modifyRequestHeaders(HttpRequest originalRequest, List<String> tempHeaders) {
        // 构建需要更新的请求头列表（仅包含原始请求中已存在的头部）
        List<HttpHeader> updatedHeaders = new ArrayList<>();
        // 构建需要添加的请求头列表（仅包含原始请求中不存在的头部）
        List<HttpHeader> addedHeaders = new ArrayList<>();
        // 构建需要移除的请求头名称列表
        List<HttpHeader> removedHeaderNames = new ArrayList<>();

        // 分类临时请求头
        for (String tempHeader : tempHeaders) {
            int colonIndex = tempHeader.indexOf(':');
            if (colonIndex > 0 && colonIndex < tempHeader.length() - 1) {
                String headerName = tempHeader.substring(0, colonIndex).trim();
                String headerValue = tempHeader.substring(colonIndex + 1).trim();
                HttpHeader header = HttpHeader.httpHeader(headerName, headerValue);

                // 检查原始请求中是否已存在同名头部
                boolean existsInOriginal = false;
                for (HttpHeader originalHeader : originalRequest.headers()) {
                    if (originalHeader.name().equalsIgnoreCase(headerName)) {
                        existsInOriginal = true;
                        break;
                    }
                }

                if (existsInOriginal) {
                    updatedHeaders.add(header);
                } else {
                    addedHeaders.add(header);
                }
            }
        }

        // 如果勾选了"避免服务器返回304响应"，则移除缓存相关的请求头
        if (configPanel != null && configPanel.isAvoid304Checked()) {
            removedHeaderNames.add(modifiedSinceHeader);
            removedHeaderNames.add(ifNoneMatchHeader);
        }

        // 先使用withUpdatedHeaders更新已存在的头部
        HttpRequest newRequest = originalRequest.withUpdatedHeaders(updatedHeaders);

        // 再使用withAddedHeaders添加新的头部
        newRequest = newRequest.withAddedHeaders(addedHeaders);
        
        // 移除指定的请求头
        if (!removedHeaderNames.isEmpty()) {
            newRequest = newRequest.withRemovedHeaders(removedHeaderNames);
        }

        return newRequest;
    }

    // 创建未授权请求
    private HttpRequest createUnauthorizedRequest(HttpRequest originalRequest, List<String> tempHeaders) {
        // 提取临时请求头的名称
        List<String> tempHeaderNames = new ArrayList<>();
        for (String tempHeader : tempHeaders) {
            int colonIndex = tempHeader.indexOf(':');
            if (colonIndex > 0) {
                String headerName = tempHeader.substring(0, colonIndex).trim();
                tempHeaderNames.add(headerName);
            }
        }

        // 构建需要更新的请求头列表
        List<HttpHeader> updatedHeaders = new ArrayList<>();
        // 构建需要移除的请求头名称列表
        List<HttpHeader> removedHeaderNames = new ArrayList<>();

        // 遍历原始请求的头部
        for (HttpHeader originalHeader : originalRequest.headers()) {
            String headerName = originalHeader.name();
            // 检查该头部是否在临时请求头中存在
            boolean shouldClear = false;
            for (String tempHeaderName : tempHeaderNames) {
                if (headerName.equalsIgnoreCase(tempHeaderName)) {
                    shouldClear = true;
                    break;
                }
            }

            // 如果需要清除，则将值置空；否则保留原值
            if (shouldClear) {
                updatedHeaders.add(HttpHeader.httpHeader(headerName, ""));
            } else {
                updatedHeaders.add(originalHeader);
            }
        }

        // 如果勾选了"避免服务器返回304响应"，则移除缓存相关的请求头
        if (configPanel != null && configPanel.isAvoid304Checked()) {
            removedHeaderNames.add(modifiedSinceHeader);
            removedHeaderNames.add(ifNoneMatchHeader);
        }

        // 使用withUpdatedHeaders更新头部
        HttpRequest request = originalRequest.withUpdatedHeaders(updatedHeaders);
        
        // 移除指定的请求头
        if (!removedHeaderNames.isEmpty()) {
            request = request.withRemovedHeaders(removedHeaderNames);
        }
        
        return request;
    }

    // 显示选中行的请求和响应信息
    private void displayRequestResponse(int rowIndex) {
        if (rowIndex >= 0 && rowIndex < requestResponseList.size()) {
            HttpRequestResponse requestResponse = requestResponseList.get(rowIndex);

            if (requestResponse.request() != null) {
                originalRequestTextArea.setText(requestResponse.request().toString());
                originalRequestTextArea.setCaretPosition(0);
            } else {
                originalRequestTextArea.setText("");
            }

            if (requestResponse.response() != null) {
                originalResponseTextArea.setText(requestResponse.response().toString());
                originalResponseTextArea.setCaretPosition(0);
            } else {
                originalResponseTextArea.setText("");
            }
        }

        // 显示修改后的请求和响应
        if (rowIndex < modifiedRequestResponseList.size() && modifiedRequestResponseList.get(rowIndex) != null) {
            HttpRequestResponse modifiedReqResp = modifiedRequestResponseList.get(rowIndex);

            if (modifiedReqResp.request() != null) {
                modifiedRequestTextArea.setText(modifiedReqResp.request().toString());
                modifiedRequestTextArea.setCaretPosition(0);
            } else {
                modifiedRequestTextArea.setText("");
            }

            if (modifiedReqResp.response() != null) {
                modifiedResponseTextArea.setText(modifiedReqResp.response().toString());
                modifiedResponseTextArea.setCaretPosition(0);
            } else {
                modifiedResponseTextArea.setText("");
            }
        } else {
            modifiedRequestTextArea.setText("");
            modifiedResponseTextArea.setText("");
        }

        // 显示未授权的请求和响应
        if (rowIndex < unauthorizedRequestResponseList.size() && unauthorizedRequestResponseList.get(rowIndex) != null) {
            HttpRequestResponse unauthorizedReqResp = unauthorizedRequestResponseList.get(rowIndex);

            if (unauthorizedReqResp.request() != null) {
                unauthorizedRequestTextArea.setText(unauthorizedReqResp.request().toString());
                unauthorizedRequestTextArea.setCaretPosition(0);
            } else {
                unauthorizedRequestTextArea.setText("");
            }

            if (unauthorizedReqResp.response() != null) {
                unauthorizedResponseTextArea.setText(unauthorizedReqResp.response().toString());
                unauthorizedResponseTextArea.setCaretPosition(0);
            } else {
                unauthorizedResponseTextArea.setText("");
            }
        } else {
            unauthorizedRequestTextArea.setText("");
            unauthorizedResponseTextArea.setText("");
        }
    }

    /**
     * 从规则面板中获取逻辑关系
     *
     * @param rulePanel 规则面板
     * @return 逻辑关系字符串 ("And" 或 "Or")
     */
    private String getLogicRelationFromRulePanel(RulePanel rulePanel) {
        return rulePanel.getLogicRelation();
    }

    // 添加清空临时请求头内容的方法
    public void clearTempHeaderContent() {
        if (configPanel != null) {
            configPanel.clearTempHeaderContent();
        }
    }
    
    // 添加设置临时请求头内容的方法
    public void setTempHeaderContent(String content) {
        if (configPanel != null) {
            configPanel.setTempHeaderContent(content);
        }
    }

    /**
     * 关闭资源
     */
    public void shutdown() {
        // 关闭正则表达式执行器
        utils.RuleUtil.shutdownRegexExecutor();
        utils.InterceptFilterUtil.shutdownRegexExecutor();
    }
    
    /**
     * 获取配置面板
     * @return ConfigPanel实例
     */
    public ConfigPanel getConfigPanel() {
        return configPanel;
    }

    /**
     * 处理单个请求的测试逻辑
     *
     * @param i 请求在列表中的索引
     * @param headerLines 临时请求头列表
     * @param isUnauthorizedCheckSelected 是否检查未授权
     * @param isIgnore204304Checked 是否忽略204/304响应
     * @param updateRenderersRef 更新渲染器的回调方法
     */
private void processRequest(
        int i,
        List<String> headerLines,
        boolean isUnauthorizedCheckSelected,
        boolean isIgnore204304Checked,
        Runnable updateRenderersRef) {

    HttpRequestResponse originalRequestResponse = requestResponseList.get(i);
    HttpRequest originalRequest = originalRequestResponse.request();
    HttpResponse originalResponse = originalRequestResponse.response();

    // 如果使用配置规则被勾选，检查是否匹配拦截过滤器规则
    if (configPanel.isUseConfigRulesChecked()) {
        if (!InterceptFilterUtil.matchesInterceptFilterRules(originalRequest, configPanel.getInterceptFilterRulePanel().getRules())) {
            LoggerUtil.logOutput("请求不匹配拦截过滤器规则，跳过测试: " + originalRequest.url());
            return;
        }
    }

    // 如果原始请求没有响应，则先发送原始请求以获取响应
    if (originalResponse == null) {
        LoggerUtil.logOutput("正在获取原始请求的响应: " + originalRequest.url());
        HttpRequestResponse sentOriginalRequestResponse = montoyaApi.http().sendRequest(originalRequest);
        
        // 更新原始请求响应列表
        requestResponseList.set(i, sentOriginalRequestResponse);
        originalResponse = sentOriginalRequestResponse.response();
        
        // 更新表格中的原始响应长度
        if (originalResponse != null) {
            String responseLength = RequestUtil.getResponseLength(originalResponse);

            final int index = i;
            final String length = responseLength;
            // 在EDT中更新UI
            SwingUtilities.invokeLater(() -> {
                tableModel.setValueAt(length, index, 3); // 原始响应长度列
            });
        } else {
            LoggerUtil.logOutput("无法获取原始请求的响应: " + originalRequest.url());
        }
    }

    // 确保原始响应存在后再继续测试
    if (originalResponse == null) {
        LoggerUtil.logOutput("跳过测试，因为无法获取原始响应: " + originalRequest.url());
        return;
    }

    // 如果勾选了"避免服务器返回304响应"，且原始响应码为304，则重新发送请求（移除If-Modified-Since和If-None-Match头）
    if (configPanel.isAvoid304Checked() && originalResponse.statusCode() == 304) {
        LoggerUtil.logOutput("检测到304响应，正在重新发送请求以避免304: " + originalRequest.url());
        
        // 移除If-Modified-Since和If-None-Match请求头
        List<HttpHeader> headersToRemove = new ArrayList<>();
        headersToRemove.add(modifiedSinceHeader);
        headersToRemove.add(ifNoneMatchHeader);
        HttpRequest requestWithout304Headers = originalRequest.withRemovedHeaders(headersToRemove);
        
        // 重新发送请求
        HttpRequestResponse resentRequestResponse = montoyaApi.http().sendRequest(requestWithout304Headers);
        
        // 如果重新发送的请求有响应，则更新原始请求响应
        if (resentRequestResponse != null && resentRequestResponse.response() != null) {
            // 更新原始请求响应列表
            requestResponseList.set(i, resentRequestResponse);
            originalResponse = resentRequestResponse.response();
            
            // 更新表格中的原始响应长度
            String responseLength = RequestUtil.getResponseLength(originalResponse);
            final int index = i;
            final String length = responseLength;
            // 在EDT中更新UI
            SwingUtilities.invokeLater(() -> {
                tableModel.setValueAt(length, index, 3); // 原始响应长度列
            });
            
            // 更新原始请求
            originalRequest = resentRequestResponse.request();
            LoggerUtil.logOutput("已重新获取非304响应: " + originalRequest.url() + " 状态码: " + originalResponse.statusCode());
        } else {
            LoggerUtil.logOutput("重新发送请求失败: " + originalRequest.url());
        }
    }

    // 如果勾选了"忽略请求响应码204|304"，且原始响应码为204或304，则跳过该请求的测试
    if (isIgnore204304Checked && (originalResponse.statusCode() == 204 || originalResponse.statusCode() == 304)) {
        LoggerUtil.logOutput("跳过响应码为 " + originalResponse.statusCode() + " 的请求: " + originalRequest.url());
        return;
    }

    // 修改请求头
    HttpRequest modifiedRequest = modifyRequestHeaders(originalRequest, headerLines);

    // 发送修改后的请求
    HttpRequestResponse modifiedRequestResponse = montoyaApi.http().sendRequest(modifiedRequest);

    // 保存修改后的请求响应
    while (modifiedRequestResponseList.size() <= i) {
        modifiedRequestResponseList.add(null);
    }
    modifiedRequestResponseList.set(i, modifiedRequestResponse);

    // 更新表格中的修改响应长度
    if (modifiedRequestResponse.response() != null) {
        HttpResponse response = modifiedRequestResponse.response();
        String responseLength = RequestUtil.getResponseLength(response);

        final int index = i;
        final String length = responseLength;
        // 在EDT中更新UI
        SwingUtilities.invokeLater(() -> {
            tableModel.setValueAt(length, index, 4); // 修改响应长度列
            // 如果未勾选"使用配置规则"复选框，则执行默认判断逻辑
            HttpRequestResponse originalReqResp = requestResponseList.get(index);
            if (!configPanel.isUseConfigRulesChecked()) {
                if (originalReqResp != null && originalReqResp.response() != null) {
                    PermissionTestUtil.updateTestResult(
                            tableModel,
                            index,
                            originalReqResp.response(),
                            modifiedRequestResponse.response(),
                            6, // 低权限结果列
                            index < lowPrivilegeRenderers.size() ? lowPrivilegeRenderers.get(index) : null,
                            updateRenderersRef
                    );
                }
            } else {
                // 使用配置规则进行判断
                if (originalReqResp != null && originalReqResp.response() != null) {
                    // 获取低权限规则面板中的逻辑关系组件
                    String logicRelation = getLogicRelationFromRulePanel(configPanel.getLowPrivilegeRulePanel());

                    PermissionTestUtil.updateTestResultWithRules(
                            tableModel,
                            index,
                            originalReqResp.response(),
                            modifiedRequestResponse.response(),
                            6, // 低权限结果列
                            index < lowPrivilegeRenderers.size() ? lowPrivilegeRenderers.get(index) : null,
                            updateRenderersRef,
                            configPanel.getLowPrivilegeRulePanel().getRules(),
                            logicRelation
                    );
                }
            }
        });
    }

    // 如果"检查未授权"复选框被选中，则执行未授权测试
    if (isUnauthorizedCheckSelected) {
        // 创建未授权请求（将原始请求中与临时请求头中相同的请求头的值置空）
        HttpRequest unauthorizedRequest = createUnauthorizedRequest(originalRequest, headerLines);

        // 发送未授权请求
        HttpRequestResponse unauthorizedRequestResponse = montoyaApi.http().sendRequest(unauthorizedRequest);

        // 保存未授权请求响应
        while (unauthorizedRequestResponseList.size() <= i) {
            unauthorizedRequestResponseList.add(null);
        }
        unauthorizedRequestResponseList.set(i, unauthorizedRequestResponse);

        // 更新表格中的未授权响应长度
        if (unauthorizedRequestResponse.response() != null) {
            HttpResponse response = unauthorizedRequestResponse.response();
            String responseLength = RequestUtil.getResponseLength(response);

            final int index = i;
            final String length = responseLength;
            // 在EDT中更新UI
            SwingUtilities.invokeLater(() -> {
                tableModel.setValueAt(length, index, 5); // 未授权响应长度列

                // 如果未勾选"使用配置规则"复选框，则执行默认判断逻辑
                HttpRequestResponse originalReqResp = requestResponseList.get(index);
                if (!configPanel.isUseConfigRulesChecked()) {
                    if (originalReqResp != null && originalReqResp.response() != null) {
                        PermissionTestUtil.updateTestResult(
                                tableModel,
                                index,
                                originalReqResp.response(),
                                unauthorizedRequestResponse.response(),
                                7, // 未授权结果列
                                index < unauthorizedRenderers.size() ? unauthorizedRenderers.get(index) : null,
                                updateRenderersRef
                        );
                    }
                } else {
                    // 使用配置规则进行判断
                    if (originalReqResp != null && originalReqResp.response() != null) {
                        // 获取未授权规则面板中的逻辑关系组件
                        String logicRelation = getLogicRelationFromRulePanel(configPanel.getUnauthorizedRulePanel());

                        PermissionTestUtil.updateTestResultWithRules(
                                tableModel,
                                index,
                                originalReqResp.response(),
                                unauthorizedRequestResponse.response(),
                                7, // 未授权结果列
                                index < unauthorizedRenderers.size() ? unauthorizedRenderers.get(index) : null,
                                updateRenderersRef,
                                configPanel.getUnauthorizedRulePanel().getRules(),
                                logicRelation
                        );
                    }
                }
            });
        }
    }
}}